package com.lcw.library.imagepicker.utils;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

/**
 * 权限申请工具类
 * 
 * 提供权限相关的工具方法：
 * - 权限检查
 * - 权限申请
 * - 权限状态判断
 * - 设置页面跳转
 * - Android版本适配
 * 
 */
public class PermissionUtil {

    /**
     * 存储权限检查
     *
     * @param context
     * @return
     */
    public static boolean checkStoragePermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && Utils.getTargetSdkVersion(context) >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用细分权限
            boolean hasImagePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED;
            boolean hasVideoPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED;
            
            // Android 14+ 检查部分选择权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                boolean hasPartialPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) == PackageManager.PERMISSION_GRANTED;
                return hasImagePermission && hasVideoPermission || hasPartialPermission;
            }
            
            return hasImagePermission && hasVideoPermission;
        } else {
            // Android 12及以下使用传统存储权限
            return ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED 
                && ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
    }

    /**
     * 检查是否有完整的媒体访问权限（非部分选择）
     *
     * @param context
     * @return
     */
    public static boolean hasFullMediaAccess(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && Utils.getTargetSdkVersion(context) >= Build.VERSION_CODES.TIRAMISU) {
            boolean hasImagePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED;
            boolean hasVideoPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED;
            return hasImagePermission && hasVideoPermission;
        } else {
            return checkStoragePermission(context);
        }
    }

    /**
     * 检查是否只有部分选择权限
     *
     * @param context
     * @return
     */
    public static boolean hasPartialMediaAccess(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            boolean hasPartialPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED) == PackageManager.PERMISSION_GRANTED;
            boolean hasFullPermission = hasFullMediaAccess(context);
            return hasPartialPermission && !hasFullPermission;
        }
        return false;
    }

    /**
     * 请求存储权限
     *
     * @param fragment
     * @param requestCode
     */
    public static void requestStoragePermission(Fragment fragment, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && Utils.getTargetSdkVersion(fragment.requireContext()) >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 请求细分权限
            String[] permissions;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                // Android 14+ 包含部分选择权限
                permissions = new String[]{
                    Manifest.permission.READ_MEDIA_IMAGES, 
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
                };
            } else {
                permissions = new String[]{
                    Manifest.permission.READ_MEDIA_IMAGES, 
                    Manifest.permission.READ_MEDIA_VIDEO
                };
            }
            
            fragment.requestPermissions(permissions, requestCode);
        } else {
            // Android 12及以下请求传统存储权限
            fragment.requestPermissions(new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE, 
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, requestCode);
        }
    }

    /**
     * 检查相机权限
     *
     * @param context
     * @return
     */
    public static boolean checkCameraPermission(Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 请求相机权限
     *
     * @param fragment
     * @param requestCode
     */
    public static void requestCameraPermission(Fragment fragment, int requestCode) {
        fragment.requestPermissions(new String[]{Manifest.permission.CAMERA}, requestCode);
    }

    /**
     * 检查权限请求结果
     *
     * @param permissions
     * @param grantResults
     * @return
     */
    public static boolean checkPermissionResult(String[] permissions, int[] grantResults) {
        if (permissions.length == 0 || grantResults.length == 0) {
            return false;
        }

        // 检查是否至少有一个权限被授予
        boolean hasPermission = false;
        for (int result : grantResults) {
            if (result == PackageManager.PERMISSION_GRANTED) {
                hasPermission = true;
                break;
            }
        }

        return hasPermission;
    }

    /**
     * 是否应该显示权限说明
     *
     * @param fragment
     * @param permission
     * @return
     */
    public static boolean shouldShowRequestPermissionRationale(Fragment fragment, String permission) {
        return fragment.shouldShowRequestPermissionRationale(permission);
    }

    /**
     * 跳转到应用设置页面
     *
     * @param context
     */
    public static void openAppSettings(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 请求更多媒体访问权限（Android 14+）
     * 当用户只授予部分选择权限时，可以调用此方法让用户选择更多媒体文件
     *
     * @param fragment
     * @param requestCode
     */
    public static void requestMoreMediaAccess(Fragment fragment, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            try {
                // 方法1：尝试使用系统媒体选择器
                Intent intent = new Intent("android.provider.action.USER_SELECT_IMAGES_FOR_APP");
                
                // 检查是否有应用可以处理这个Intent
                if (intent.resolveActivity(fragment.requireContext().getPackageManager()) != null) {
                    fragment.startActivityForResult(intent, requestCode);
                    return;
                }
                
                // 方法2：尝试使用MediaStore的Photo Picker
                intent = new Intent("android.provider.action.PICK_IMAGES");
                intent.setType("image/*");
                intent.putExtra("android.provider.extra.PICK_IMAGES_MAX", Integer.MAX_VALUE);
                
                if (intent.resolveActivity(fragment.requireContext().getPackageManager()) != null) {
                    fragment.startActivityForResult(intent, requestCode);
                    return;
                }
                
                // 方法3：回退到重新请求权限
                requestStoragePermission(fragment, requestCode);
                
            } catch (Exception e) {
                // 如果所有方法都失败，回退到权限请求
                requestStoragePermission(fragment, requestCode);
            }
        } else {
            // Android 14以下，直接重新请求权限
            requestStoragePermission(fragment, requestCode);
        }
    }

    /**
     * 检查是否可以请求更多媒体访问权限
     *
     * @param context
     * @return
     */
    public static boolean canRequestMoreMediaAccess(Context context) {
        // Android 14+ 且用户有部分权限时显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && hasPartialMediaAccess(context)) {
            return true;
        }
        
        // Android 13+ 且用户没有完整权限时也可以显示，让用户重新请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && !hasFullMediaAccess(context)) {
            return true;
        }
        
        return false;
    }
}
